from flask import Flask, request, send_file
from flask_cors import CORS
from routes.string_replace import StringReplacer, get_bing_wallpaper
from io import BytesIO
import os

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes

@app.route('/replace', methods=['POST'])
def replace_strings():
    """处理字符串替换请求"""
    if 'original_file' not in request.files or 'replace_file' not in request.files:
        return {'error': '请同时选择原始文件和替换文件'}, 400
    
    original_file = request.files['original_file']
    replace_file = request.files['replace_file']
    
    if original_file.filename == '' or replace_file.filename == '':
        return {'error': '请选择有效的文件'}, 400
    
    if not (original_file.filename.endswith('.xml') and replace_file.filename.endswith('.xml')):
        return {'error': '文件格式必须为 .xml'}, 400
    
    try:
        # 创建临时文件
        original_content = original_file.read().decode('utf-8')
        replace_content = replace_file.read().decode('utf-8')
        
        # 使用字符串替换器处理
        replacer = StringReplacer(original_content, replace_content)
        result_content = replacer.process()
        
        # 创建内存文件
        memory_file = BytesIO()
        memory_file.write(result_content.encode('utf-8'))
        memory_file.seek(0)
        
        # 生成输出文件名
        original_name = os.path.splitext(original_file.filename)[0]
        output_filename = f"{original_name}_replaced.xml"
        
        return send_file(
            memory_file,
            download_name=output_filename,
            as_attachment=True,
            mimetype='application/xml'
        )
        
    except Exception as e:
        return {'error': f'处理文件时出错: {str(e)}'}, 500

@app.route('/bing-wallpaper', methods=['GET'])
def bing_wallpaper():
    """获取必应每日壁纸"""
    try:
        image_url = get_bing_wallpaper()
        return {'url': image_url}
    except Exception as e:
        return {'error': f'获取壁纸失败: {str(e)}'}, 500

@app.route('/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return {'status': 'ok', 'message': 'Replace Strings API is running'}

if __name__ == '__main__':
    app.run(debug=True, port=5000)
